package com.sgb.kjwl.view.ui.activity.house;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLeaseUseMapBinding;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

/**
 * 地图查找(出租)
 */
public class LeaseUseMapActivity extends AppActivity implements
        LocationSource,
        AMapLocationListener,
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener {

    private ActivityLeaseUseMapBinding binding;

    private Bundle bundle = new Bundle();
    private AMap mAMap;
    private Marker mGPSMarker;             //定位位置显示
    private AMapLocation location;
    private OnLocationChangedListener mListener;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //你编码对象
    private GeocodeSearch geocoderSearch;

    private MarkerOptions markOptions;
    private LatLng latLng;
    private String addressName;


    private boolean isHaveData = false;

    public static void start(Context context, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseUseMapActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private void getArgument() {
        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            bundle = intent.getExtras();
        }
        addressName = bundle.getString("text");
        String title = bundle.getString("title");
        latLng = new LatLng(bundle.getDouble("lat"), bundle.getDouble("lon"));

        if (!("图选").equals(title)) {
            isHaveData = true;
            setMarket(latLng, "", addressName);
            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
            binding.mapAddress.tvAddr.setText(addressName);
        } else {
            String latitude = SharedPreferenceUtil.getInstance().getSaveStringData("Lease_Latitude", "");
            String longitude = SharedPreferenceUtil.getInstance().getSaveStringData("Lease_Longitude", "");
            if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
                latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
            }

//            isHaveData = false;
//            mAMap.setLocationSource(this);
//            mAMap.setMyLocationEnabled(true);//开启定位
//            requestPermission();//获取定位权限
        }

    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_lease_use_map);
        initMap(savedInstanceState);
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void init() {
        getArgument();
    }


    @Override
    protected void initView() {
        binding.topLayout.titleView.setText("选择工作地");
        binding.topLayout.ivBack.setOnClickListener(v -> finish());
        binding.mapAddress.btQueding.setOnClickListener(view -> toMapForBundle());
    }

    private void toMapForBundle() {
        Bundle bundle = new Bundle();
        bundle.putString("title", addressName);
        bundle.putString("text", addressName);
        bundle.putDouble("lat", latLng.latitude);
        bundle.putDouble("lon", latLng.longitude);
        LeaseHallMapActivity.startForBundle(getActivity(), bundle);
        finish();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置定位权限
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (!isHaveData) {
                        mLocationClient.startLocation();//开启定位
                    }
//                } else {//无定位权限，默认显示北京北京市东城区前门东大街11号 经纬度和地址
//                    LatLng lat = new LatLng(39.903114318847656, 116.39775848388672);
//                    mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lat, 16));
//                    addMarker2(latLng, "北京市东城区前门东大街11号");
//                    if (!isHaveData) {
//                        MToast.showToast(getActivity(), "无法获取当前位置,请输入使用地点");
//                    }
                }
                return;
        }
    }


    //初始化地图
    private void initMap(Bundle savedInstanceState) {
        binding.mapView.onCreate(savedInstanceState);
        mAMap = binding.mapView.getMap();
        mAMap.setOnCameraChangeListener(this);//设置地图拖动监听
        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(this);

        //导航箭头定位的小图标，这里自定义一张图片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色  这样圆圈就没有了，看不到了
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(16)); //缩放比例

        //设置amap的属性
        UiSettings settings = mAMap.getUiSettings();
        settings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        settings.setZoomControlsEnabled(false);//隐藏放大缩小

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        location = aMapLocation;
        if (mListener != null && location != null && location.getErrorCode() == 0) {
            mListener.onLocationChanged(location);// 显示系统箭头
            mLocationClient.stopLocation();
//        } else {
//            MToast.showToast(getActivity(), "无法获取当前位置,请输入使用地点");
        }
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if (mGPSMarker.isInfoWindowShown()) {
            mGPSMarker.hideInfoWindow();
            binding.mapView.invalidate();
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        latLng = cameraPosition.target;
        getAddress(latLng);
    }

    /**
     * 根据经纬度得到地址
     */
    public void getAddress(final LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        //初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);

        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        if (!isHaveData) {
            mLocationClient.startLocation();
        }

    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                // 逆转地里编码不是每次都可以得到对应地图上的opi
                addressName = result.getRegeocodeAddress().getFormatAddress();

                binding.mapAddress.tvAddr.setText(addressName);
                setMarket(latLng, "", addressName);
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }

    private void setMarket(LatLng latLng, String title, String content) {
        binding.mapView.getMap().clear();
        if (mGPSMarker != null) {
            mGPSMarker.remove();
        }
        //获取屏幕宽高
        WindowManager wm = getWindowManager();
        int width = (wm.getDefaultDisplay().getWidth()) / 2;
        int height = ((wm.getDefaultDisplay().getHeight()) / 2) - 200;
        markOptions = new MarkerOptions();
        markOptions.draggable(false);
        binding.mapView.getMap().setInfoWindowAdapter(new MapInfoWinAdapter(this));
        markOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_location));
//        markOptions.icon(BitmapDescriptorFactory.fromView(getInfoWindow(content)));
        //   markOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.map_location))).anchor(0.5f, 0.7f);
        //设置一个角标
        mGPSMarker = mAMap.addMarker(markOptions);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        mGPSMarker.setTitle(title);
        mGPSMarker.setSnippet(content);
        //设置像素坐标
        mGPSMarker.setPositionByPixels(width, height);
        mGPSMarker.showInfoWindow();
        binding.mapView.invalidate();
    }

    private MarkerOptions markerOption;

//    private void addMarker2(LatLng la, String addr) {
//        markerOption = new MarkerOptions()
//                .position(la)
//                .icon(BitmapDescriptorFactory.fromView(getInfoWindow(addr)))
//                //  .snippet(addr)
////                .period(1000)
//                .draggable(true);
//        mAMap.addMarker(markerOption).hideInfoWindow();
//    }

//
//    public View getInfoWindow(String addr) {
//        View view = View.inflate(getActivity(), R.layout.marker_info_layout, null);
//        TextView tv_addr = view.findViewById(R.id.tv_addr);
//        tv_addr.setText(addr);
//        return view;
//    }

}
